package leetcode_字符串._01字符;

/**
 * @author yzh
 * @version 1.0
 * @date 2021/5/25 22:00
 * 字符串转换整数 (atoi)
 * 算法：字符串
 * 主要判断数字有没有溢出
 * max = (max / 10) * 10 + max % 10
 * num * 10 + next < max ==> num * 10 + next < (max / 10) * 10 + 7
 * num * 10 - (max / 10) * 10 < 7 - next ==> (num - max / 10) * 10 < 7 - next
 * 先取出左边的空格
 * 获取是正数还是负数
 * 遇到不是数字，则直接结束循环
 */
public class _8 {
    public static void main(String[] args) {
        System.out.println(new _8().myAtoi("-2147483649"));
//        System.out.println(new _8().myAtoi("   -42"));
    }

    public int myAtoi(String str) {
        int res = 0, len = str.length();
        char[] array = str.toCharArray();
        int index = 0;
        while (index < len && array[index] == ' ') ++index;
        if (index == len) return res;
        int flag = 1;
        if (array[index] == '+') ++index;
        else if (array[index] == '-') {
            flag = -1;
            ++index;
        }
        int min = Integer.MIN_VALUE / 10, max = Integer.MAX_VALUE / 10;
        while (index < len) {
            char c = array[index];
            if (c < '0' || c > '9') break;
            if (res > max || res == max && (c - '0') > 7) return Integer.MAX_VALUE;
            if (res < min || res == min && (c - '0') > 8) return Integer.MIN_VALUE;
            res = res * 10 + (c - '0') * flag;
            ++index;
        }
        return res;
    }

}
